# -*- coding: utf-8 -*-
# standard
import os
import sys

# third

# local
_P_PATH =  os.path.dirname(os.path.dirname(os.path.realpath(__file__)))
if _P_PATH not in sys.path:
    sys.path.append(_P_PATH)
from functions import *


"""
@Title:   查询下载失败的信息，修复其中可以再次下载的部分
@File: 统计下载失败的视频信息.py
@Author: walle 2024年01日02日 15时37分30秒
@Version: 1.0.0
@Desc: 
这个和 修复数据库中被ban的记录.py  文件的效果是基本一样， 但是本文件更细致
"""

def find_reason(error: str, url: str):
    if error.startswith("API解析失败"):
        # print(url)
        reason = "视频失效"
    elif error.endswith("403"):
        print(url)
        reason = "重新下载"
    elif error.endswith("500"):
        print(url)
        reason = "重新下载"
    elif error.endswith("503"):
        print(url)
        reason = "重新下载"
    elif error.startswith("下载出错"):
        # print(url)
        reason = "重新下载"
    elif "[Errno 111] Connection refused" in error:
        reason = "私有视频"
    elif "Read timed out." in error:
        # print(url)
        reason = "重新下载"
    elif "ChunkedEncodingError" in error:
        # print(url)
        reason = "可以在线观看，但是下载会抛出 ChunkedEncodingError 错误"
    elif "ConnectionResetError(104, 'Connection reset by peer'))" in error:
        # print(url)
        reason = "可以在线观看，但是下载会抛出 ConnectionResetError 错误"
    else:
        print(error)
        print(url)
        reason = "未知错误"
        
    return reason


def main():
    db_session = new_db_session()
    cond = and_(
        MediaFileOrm.error != "",
    )
    files = [{
        "key": x.key,
        "page_url": x.page_url,
        "raw_error": x.error,
        "error": find_reason(x.error, x.page_url),
    } for x in db_session.query(MediaFileOrm).filter(cond)]
    keys = []
    for file in files:
        if file['error'] == "重新下载":
            keys.append(file['key'])
    logger.debug(f"找到 {len(keys)} 个可以重新下载的文件")
    db_session.query(MediaFileOrm).filter(MediaFileOrm.key.in_(keys)).update({"error": ""})
    db_session.commit()
    db_session.close()
    # 整理成字典格式
    data = {
        "total": len(files),
        "medias": [{"key": x['key'], "page_url": x['page_url'], "error": x['error']} for x in files],
    }

    # 写入
    bad_medias_path = os.path.join(_P_PATH, "test", "lrs3_bad_medias.json")
    with open(bad_medias_path, "w", encoding="utf-8") as f:
        json.dump(data, f, ensure_ascii=False, indent=4)
    print(f"已将 {len(files)} 个文件写入 {bad_medias_path}")


if __name__ == '__main__':
    main()
    pass